const app = getApp()
const request = require('../../../utils/request.js');
Page({
  data: {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },

  // 原密码输入
  onOldPasswordInput: function(e) {
    this.setData({
      oldPassword: e.detail.value
    })
  },

  // 新密码输入
  onNewPasswordInput: function(e) {
    this.setData({
      newPassword: e.detail.value
    })
  },

  // 确认密码输入
  onConfirmPasswordInput: function(e) {
    this.setData({
      confirmPassword: e.detail.value
    })
  },

  // 表单验证
  validateForm: function() {
    const { oldPassword, newPassword, confirmPassword } = this.data
    
    if (!oldPassword) {
      wx.showToast({
        title: '请输入原密码',
        icon: 'none'
      })
      return false
    }

    if (!newPassword) {
      wx.showToast({
        title: '请输入新密码',
        icon: 'none'
      })
      return false
    }

    if (newPassword.length < 6 || newPassword.length > 20) {
      wx.showToast({
        title: '新密码长度应在6-20个字符之间',
        icon: 'none'
      })
      return false
    }

    if (newPassword === oldPassword) {
      wx.showToast({
        title: '新密码不能与原密码相同',
        icon: 'none'
      })
      return false
    }

    if (!confirmPassword) {
      wx.showToast({
        title: '请确认新密码',
        icon: 'none'
      })
      return false
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次输入的新密码不一致',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 提交修改
  submitChange: function() {
    if (!this.validateForm()) return

    wx.showLoading({
      title: '修改中...',
    })

    const { oldPassword, newPassword } = this.data

    request.request({
      url: `${app.globalData.baseUrl}/api/user/change-password`,
      method: 'POST',
      data: {
        oldPassword,
        newPassword
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          })
          // 修改成功后返回上一页
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.data.message || '修改失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
}) 